import 'package:flutter/material.dart';
import 'package:dartdap/dartdap.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'LDAP AD 登录',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const LoginScreen(),
    );
  }
}

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController _domainController = TextEditingController();
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  String _resultMessage = '';

  Future<void> _login() async {
    String domain = _domainController.text.trim();
    String username = _usernameController.text.trim();
    String password = _passwordController.text.trim();

    if (domain.isEmpty || username.isEmpty || password.isEmpty) {
      setState(() {
        _resultMessage = "⚠️ 请填写所有字段";
      });
      return;
    }

    String ldapHost = domain;
    int ldapPort = 389; // AD LDAP 端口（默认 389）
    DN baseDN = DN("DC=${domain.replaceAll('.', ',DC=')}"); // 生成 Base DN

    var ldap = LdapConnection(
      host: ldapHost,
      port: ldapPort,
      ssl: false,
    );

    try {
      await ldap.bind(); // 匿名绑定（如果服务器允许）

      // 🔍 1. 搜索用户 DN
      var filter = Filter.equals("sAMAccountName", username);
      var searchResult = await ldap.search(
        
        baseDN, 
        filter, 
        ["dn"]
        
        );

      String? userDN;
      await for (var entry in searchResult.stream) {
        userDN = entry.dn.toString();
        break; // 取第一个匹配项
      }

      if (userDN == null) {
        setState(() {
          _resultMessage = "❌ 用户不存在";
        });
        await ldap.close();
        return;
      }

      print("🔍 用户 DN: $userDN");

      // 🔐 2. 使用用户凭据绑定
      var userLdap = LdapConnection(
        host: ldapHost,
        port: ldapPort,
        ssl: false,
      );
      // await userLdap.bind(userDN, password);
      await ldap.bind(dn: DN(userDN), password:password); 

      // 🔍 3. 获取用户详细信息
      var userInfo = await userLdap.search(
        baseDN,
        Filter.equals("sAMAccountName", username),
        ["displayName", "mail"],
      );

      String name = "未知";
      String email = "未知";

      await for (var entry in userInfo.stream) {
        name = entry.attributes["displayName"]?.values.first ?? "未知";
        email = entry.attributes["mail"]?.values.first ?? "未知";
      }

      setState(() {
        _resultMessage = "✅ 登录成功!\n"
            "用户名: $username\n"
            "姓名: $name\n"
            "邮箱: $email";
      });

      await userLdap.close();
    } catch (e) {
      setState(() {
        _resultMessage = "❌ 登录失败: $e";
        print(e)     ;
      });
    } finally {
      await ldap.close();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue[100],
      body: Center(
        child: Container(
          width: 400,
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(color: Colors.black26, blurRadius: 10, spreadRadius: 2),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text("登录", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
              const SizedBox(height: 20),
              _buildTextField("域 名:", _domainController, "输入AD域名"),
              _buildTextField("用户:", _usernameController, "输入管理员账户"),
              _buildTextField("密 码:", _passwordController, "输入密码", obscureText: true),
              const SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  ElevatedButton(onPressed: _login, child: const Text("登录")),
                  ElevatedButton(
                    onPressed: () => setState(() => _resultMessage = ""),
                    child: const Text("退出"),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              Text(_resultMessage, textAlign: TextAlign.center, style: const TextStyle(fontSize: 16)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTextField(String label, TextEditingController controller, String hint, {bool obscureText = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          SizedBox(width: 60, child: Text(label, style: const TextStyle(fontSize: 16))),
          Expanded(
            child: TextField(
              controller: controller,
              obscureText: obscureText,
              decoration: InputDecoration(
                hintText: hint,
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                contentPadding: const EdgeInsets.symmetric(horizontal: 10),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
